import { cloneDeep, lodashMap as map, template as lodashTemplate } from "lodash-es";
import { failres, okres } from "../../config/resUtil.js";

import { Controller, App, Post, Body } from "@midwayjs/core";
import { Application } from "../../interface.js";

// 一些默认的公共的操作
export class <%=tableName%>Controller {
  @App("koa")
  app: Application;



  async querybuildcomon(query, body, ispage = true) {
    <% _.map(colkeys, keyitem => { %>
        if (body?.['<%=keyitem.Field%>']) {
        query.andWhere("<%=keyitem.Field%>", body?.['<%=keyitem.Field%>']);
      }
      <% }) %>


      if (ispage) {
            if (body?.pageSize) {
              query.limit(body?.pageSize)
            }


var pageNum=body?.pageNum ||1
            if (pageNum) {
              query.offset( (pageNum-1 )* body?.pageSize )
            }
      }



  }

  getDb() {
    return this.app['<%=getdbname(datasourceDto)%>']
  }



  async getlist(body) {
    console.log("开始 列表 ");

    var query = this.getDb().select().from("<%=tableName%>");
    var query1 = this.getDb().select().from("<%=tableName%>");

    //获取默认字段
    this.querybuildcomon(query, body);
    this.querybuildcomon(query1, body, false);
    var totalresults = await query1.count('id')
    var total = totalresults?.[0]?.['count(`id`)'];
    console.log('total :', total);

    query.orderBy('id','desc')

    return okres(await query, { total });
  }

  async getbyitem(body) {
    console.log("开始 获取单个 id:", body?.id);
    var query = this.getDb().select("*").from("<%=tableName%>");
    console.log("body :", body);


    if (!body?.id) {
      return okres(null);
    }

    if ((!body) || !Object.keys(body).length) {
      return okres(null);
    }

    if (body?.id) {
      query.andWhere("id", '=', body?.id);
    } else {

    }


    console.log("query :", query);

    var lists = await query;
    var one = lists?.[0];
    console.log('开始sql  :', one);

    return okres(one);
  }

  async 删除(body) {
    if (!body.id) {
      return failres('没有id')
    }
    var delresult = await this.getDb()('<%=tableName%>').where('id', body.id).del();
    return okres(delresult);
  }

  async addorupdate(body) {
    console.log("开始 新增or修改 ");
    var rsiltonme = await this.getbyitem(body);
    var one = rsiltonme && rsiltonme.data;
    console.log("one :", one);

    var result = undefined;
    if (one?.id) {
      var __params = cloneDeep(body)
      delete __params.id
      result = await this.getDb()("<%=tableName%>").where("id", '=', one.id).update(__params);
    } else {
      // 新增
      var __params = cloneDeep(body)
      delete __params.id
      result = await this.getDb()("<%=tableName%>").insert(__params);
    }
    return okres(result);
  }

}